package com.hupu.jrs.data

import com.hupu.jrs.Logger
import com.hupu.jrs.data.local.ForumLocalDataSource
import com.hupu.jrs.data.remote.ForumRemoteDataSource
import rx.Observable
import javax.inject.Inject

/**
 * Created by sll on 2016/6/3.
 */
class ForumRepository @Inject
constructor(private val mForumLocalDataSource: ForumLocalDataSource,
            private val mForumRemoteDataSource: ForumRemoteDataSource) : ForumDataSource {

    override fun getForumList(forumId: String): Observable<List<Forum>> {
        Logger.d("getForumList:" + forumId)
        val remote = mForumRemoteDataSource.getForumList(forumId)
        val local = mForumLocalDataSource.getForumList(forumId)

        val remoteWithLocalUpdate = remote.doOnNext { fora ->
            if (fora != null) {
                for (forum in fora) {
                    mForumLocalDataSource.saveForum(forum)
                }
            }
        }
        return if (forumId == "0") {  //我的论坛强制刷新
            remoteWithLocalUpdate
        } else Observable.concat(local, remoteWithLocalUpdate).first { fora -> fora != null && !fora.isEmpty() }

    }

    override fun removeForum(fid: String): Observable<Boolean> {
        return null!!
    }
}
